import os
from gevent import monkey
monkey.patch_all()      # 用于将标准库中大部分阻塞式调用修改为协作式运行
import gevent

from Base import SockerBase


class Sender:
    def __init__(self, conn):
        self.conn = SockerBase(conn=conn)

    def send_file(self):
        self.g = gevent.spawn(self._do_send_file)
        self.g.join()

    def send_check(self):
        self.request = self.conn.myrece()
        self.path = self.request.get('path', 'None')
        if self._check_file():
            self.conn.mysend({'able': True})
            return True
        else:
            self.conn.mysend({'able': False})
            return False

    def _check_file(self):
        if not os.path.exists(self.path):
            self.conn.print('File does not exit')
            return False
        else:
            return True

    def _do_send_file(self):
        with open(self.path, 'rb') as f:
            self.conn.mysend(f.read())
        self.conn.print('Send file successfully')
        self.g.kill()


class Server:
    """ 初始化 启动"""
    def __init__(self, port=50000):
        self.sock = SockerBase(port)
        self.sock.init_server(10)
        self.sender_line = []

    def start(self):
        while True:
            self.sock.print('Before request')
            conn = self.sock.start_listen()
            self.start_gevent_send(conn)

    def start_gevent_send(self, conn):
        sender = Sender(conn)
        if sender.send_check():
            self.sock.print('Accept request')
            self.sender_line.append(sender)
            self.sender_line[-1].send_file()
        else:
            self.sock.print('Refuse request')
            del sender

if __name__ == '__main__':
    s = Server()
    s.start()